import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { userApi } from '@/services/userApi'
import type { User } from '@/types/api'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态
  const users = ref<User[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const selectedUser = ref<User | null>(null)
  const searchQuery = ref('')
  const pageSize = ref(10)
  const currentPage = ref(1)

  // 计算属性
  const userCount = computed(() => users.value.length)
  const hasUsers = computed(() => users.value.length > 0)
  const isEmpty = computed(() => users.value.length === 0 && !loading.value)

  // 搜索和筛选相关计算属性
  const filteredUsers = computed(() => {
    if (!searchQuery.value.trim()) {
      return users.value
    }
    const query = searchQuery.value.toLowerCase().trim()
    return users.value.filter(
      (user) =>
        user.name.toLowerCase().includes(query) ||
        user.email.toLowerCase().includes(query) ||
        user.id.toString().includes(query),
    )
  })

  const filteredUserCount = computed(() => filteredUsers.value.length)

  // 分页相关计算属性
  const totalPages = computed(() => Math.ceil(filteredUsers.value.length / pageSize.value))

  const paginatedUsers = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredUsers.value.slice(start, end)
  })

  // 用户状态相关计算属性
  const getUserById = computed(() => {
    return (id: number) => users.value.find((user) => user.id === id)
  })

  const isUserSelected = computed(() => selectedUser.value !== null)

  // 操作方法
  const fetchUsers = async (showSuccessMessage = false) => {
    try {
      loading.value = true
      error.value = null
      const data = await userApi.getUsers()
      users.value = data
      if (showSuccessMessage && data.length > 0) {
        ElMessage.success(`成功加载 ${data.length} 个用户`)
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取用户数据失败'
      error.value = errorMessage
      // console.error('Error fetching users:', err)
      // 不在这里显示错误消息，由API拦截器处理
    } finally {
      loading.value = false
    }
  }

  const fetchUserById = async (id: number): Promise<User | null> => {
    try {
      loading.value = true
      error.value = null
      const user = await userApi.getUserById(id)
      // 同时更新选中的用户
      selectedUser.value = user
      return user
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取用户失败'
      error.value = errorMessage
      // console.error('Error fetching user:', err)
      return null
    } finally {
      loading.value = false
    }
  }

  const createUser = async (userData: Omit<User, 'id'>) => {
    try {
      loading.value = true
      error.value = null
      const newUser = await userApi.createUser(userData)
      users.value.unshift(newUser) // 新用户显示在列表顶部
      // 重置分页到第一页以显示新用户
      currentPage.value = 1
      return newUser
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '创建用户失败'
      error.value = errorMessage
      // console.error('Error creating user:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  const updateUser = async (id: number, userData: Partial<User>) => {
    try {
      loading.value = true
      error.value = null
      const updatedUser = await userApi.updateUser(id, userData)
      const index = users.value.findIndex((user) => user.id === id)
      if (index !== -1) {
        users.value[index] = updatedUser
        // 如果更新的是当前选中的用户，也更新选中状态
        if (selectedUser.value?.id === id) {
          selectedUser.value = updatedUser
        }
      }
      return updatedUser
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '更新用户失败'
      error.value = errorMessage
      // console.error('Error updating user:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  const deleteUser = async (id: number) => {
    try {
      loading.value = true
      error.value = null
      await userApi.deleteUser(id)
      const index = users.value.findIndex((user) => user.id === id)
      if (index !== -1) {
        users.value.splice(index, 1)
        // 如果删除的是当前选中的用户，清除选中状态
        if (selectedUser.value?.id === id) {
          selectedUser.value = null
        }
        // 如果当前页没有数据了，跳转到上一页
        if (paginatedUsers.value.length === 0 && currentPage.value > 1) {
          currentPage.value = currentPage.value - 1
        }
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '删除用户失败'
      error.value = errorMessage
      // console.error('Error deleting user:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  // 工具方法
  const clearError = () => {
    error.value = null
  }

  const resetStore = () => {
    users.value = []
    loading.value = false
    error.value = null
    selectedUser.value = null
    searchQuery.value = ''
    currentPage.value = 1
  }

  // 选中用户相关方法
  const selectUser = (user: User | null) => {
    selectedUser.value = user
  }

  const clearSelection = () => {
    selectedUser.value = null
  }

  // 搜索相关方法
  const setSearchQuery = (query: string) => {
    searchQuery.value = query
    currentPage.value = 1 // 搜索时重置到第一页
  }

  const clearSearch = () => {
    searchQuery.value = ''
    currentPage.value = 1
  }

  // 分页相关方法
  const setCurrentPage = (page: number) => {
    if (page >= 1 && page <= totalPages.value) {
      currentPage.value = page
    }
  }

  const setPageSize = (size: number) => {
    pageSize.value = size
    currentPage.value = 1 // 改变页大小时重置到第一页
  }

  const nextPage = () => {
    if (currentPage.value < totalPages.value) {
      currentPage.value++
    }
  }

  const prevPage = () => {
    if (currentPage.value > 1) {
      currentPage.value--
    }
  }

  // 批量操作方法
  const deleteMultipleUsers = async (userIds: number[]) => {
    try {
      loading.value = true
      error.value = null

      // 串行删除以避免并发问题
      for (const id of userIds) {
        await userApi.deleteUser(id)
        const index = users.value.findIndex((user) => user.id === id)
        if (index !== -1) {
          users.value.splice(index, 1)
        }
      }

      // 清除选中状态如果被删除
      if (selectedUser.value && userIds.includes(selectedUser.value.id)) {
        selectedUser.value = null
      }

      ElMessage.success(`成功删除 ${userIds.length} 个用户`)
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '批量删除用户失败'
      error.value = errorMessage
      // console.error('Error deleting multiple users:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  // 用户统计方法
  const getUserStats = () => {
    const totalUsers = users.value.length
    const emailDomains = users.value.reduce(
      (acc, user) => {
        const domain = user.email.split('@')[1]
        acc[domain] = (acc[domain] || 0) + 1
        return acc
      },
      {} as Record<string, number>,
    )

    return {
      totalUsers,
      emailDomains,
      mostCommonDomain: Object.keys(emailDomains).reduce((a, b) =>
        emailDomains[a] > emailDomains[b] ? a : b,
      ),
    }
  }

  return {
    // 基础状态
    users,
    loading,
    error,
    selectedUser,
    searchQuery,
    pageSize,
    currentPage,

    // 计算属性
    userCount,
    hasUsers,
    isEmpty,
    filteredUsers,
    filteredUserCount,
    totalPages,
    paginatedUsers,
    getUserById,
    isUserSelected,

    // 基本 CRUD 方法
    fetchUsers,
    fetchUserById,
    createUser,
    updateUser,
    deleteUser,

    // 工具方法
    clearError,
    resetStore,

    // 选中用户方法
    selectUser,
    clearSelection,

    // 搜索方法
    setSearchQuery,
    clearSearch,

    // 分页方法
    setCurrentPage,
    setPageSize,
    nextPage,
    prevPage,

    // 批量操作
    deleteMultipleUsers,

    // 统计方法
    getUserStats,
  }
})
